//引入express mvc框架
const express = require("express");
const db = require('../modules/DBhelper');
const moment = require('moment');
//创建路由
let router = express.Router();

//加入购物车
router.post('/add', async function (request, response, next) {
    //获取前端数据
    let cartObj = request.body;

    //先查询一下购物车清单里是否有该项目
    let sql = 'SELECT * FROM `cart` WHERE `u_id`=? AND `c_name`=? ;';
    let param = [
        cartObj.uId,
        cartObj.cName
    ];
    let result = await db.exec(sql, param);
    let isAddCart = result && result.length >= 1;

    //如果购物车内已经存在该商品则修改其数量和总金额
    if (isAddCart) {
        let sqlUpdate = "UPDATE `cart` SET `c_num`=`c_num`+?, `c_total`=`c_num`*`c_price`, `c_status`='1' WHERE `u_id`=? AND `c_name`=? ;";
        let paramUpdate = [
            cartObj.cNum,
            cartObj.uId,
            cartObj.cName
        ];

        try {
            let resultUpdate = await db.exec(sqlUpdate, paramUpdate);
            let isUpdate = resultUpdate && resultUpdate.affectedRows >= 1;
            response.json({
                msg: isUpdate ? '加入购物车成功' : '加入购物车失败',
                status: isUpdate ? 200 : -200,
                model: 'update'
            })
        } catch (e) {
            response.json({
                msg: '意外错误',
                status: -200,
                e
            })
        }
    } else {//如果是第一次加入购物车,则直接加入
        let sqlInsert = 'INSERT INTO `cart`(`u_id`,`c_name`,`c_price`,`c_num`,`c_total`,`c_img`,`c_createtime`) VALUE(?,?,?,?,?,?,?) ;';
        let paramInsert = [
            cartObj.uId,
            cartObj.cName,
            cartObj.cPrice,
            cartObj.cNum,
            cartObj.cPrice * cartObj.cNum,
            cartObj.cImg,
            moment().format("YYYY-MM-DD HH:mm:ss")
        ]
        try {
            let resultInsert = await db.exec(sqlInsert, paramInsert);
            let isInsert = resultInsert && resultInsert.affectedRows >= 1;
            response.json({
                msg: isInsert ? '加入购物车成功' : '加入购物车失败',
                status: isInsert ? 200 : -200,
                model: 'insert'
            });
        } catch (e) {
            response.json({
                msg: '意外错误',
                status: -200,
                e
            });
        }
    }
})

//根据用户id查询购物车
router.get('/query', async function (request, response, next) {
    //获取前端数据
    try {
        let userId = request.query.uId;
        let sql = "SELECT * FROM `cart` WHERE `u_id`=? AND c_status='1' ;";
        let resultQuery = await db.exec(sql, [userId]);
        response.json({
            msg: '查询成功',
            status: 200,
            data: resultQuery
        })
    } catch (e) {
        response.json({
            msg: '查询失败',
            status: -200,
            e
        })
    }
})

//修改购物车里的数量
router.post('/modify', async function (request, response, next) {
    let param = [
        request.body.cNum,
        request.body.cId
    ]
    let sql = "UPDATE `cart` SET `c_num`=?, `c_total`=`c_num`*`c_price` WHERE `c_id`=? ;";

    try {
        let result = await db.exec(sql, param);
        let isModify = result && result.affectedRows >= 1;
        response.json({
            msg: isModify ? '修改成功' : '修改失败',
            status: isModify ? 200 : -200
        });
    } catch (e) {
        response.json({
            msg: '意外错误',
            status: -200,
            e
        })
    }
})

//删除购物车中的商品
router.post('/delete', async function (request, response, next) {
    let param = [request.body.cId];
    //软删除
    let sql = "UPDATE `cart` SET `c_num`=0,`c_total`=0, `c_status`='0', `c_desc`=0 WHERE `c_id`=? ;";
    try {
        let result = await db.exec(sql, param);
        let isDelete = result && result.affectedRows >= 1;
        response.json({
            msg: isDelete ? '删除成功' : "删除失败",
            status: isDelete ? 200 : -200
        })
    } catch (e) {
        response.json({
            msg: '意外错误',
            status: -200,
            e
        })
    }

});

//删除选中效果
router.post('/deleteSelected', async function (request, response, next) {
    let param = [request.body.uId];
    let sql = "UPDATE `cart` SET `c_num`=0,`c_total`=0, `c_status`='0', `c_desc`=0 WHERE `u_id`=? AND `c_desc`=1 ;";
    try {
        let result = await db.exec(sql, param);
        let isSuccess = result && result.affectedRows >= 1
        response.json({
            msg: isSuccess ? '删除成功' : '删除失败',
            status: isSuccess ? 200 : -200
        });
    } catch (e) {
        response.json({
            msg: '意外错误',
            status: -200,
            e
        })
    }
})

//选中效果
router.post('/selected', async function (request, response, next) {
    let param = [request.body.cDesc, request.body.cId];
    let sql = 'UPDATE `cart` SET `c_desc`=? WHERE `c_id`=? ;';
    try {
        await db.exec(sql, param);
        response.json({
            msg: '选中成功',
            status: 200
        })
    } catch (e) {
        response.json({
            msg: '意外错误',
            status: -200,
            e
        })
    }
})

//全选效果
router.post('/selectAll', async function (request, response, next) {
    let param = [request.body.cDesc, request.body.uId];
    let sql = 'UPDATE `cart` SET `c_desc`=? WHERE `u_id`=? ;';
    try {
        await db.exec(sql, param);
        response.json({
            msg: '选中成功',
            status: 200
        })
    } catch (e) {
        response.json({
            msg: '意外错误',
            status: -200,
            e
        })
    }
})

//暴露出去
module.exports = {router};